package calao.storage;

import java.util.Iterator;
import java.util.Vector;

public class Schema 
implements Iterable<SchemaElement>
{
	
	boolean registered = false;
	Vector<SchemaElement> elements = new Vector<SchemaElement>();
	
	public void add(SchemaElement... elements)
	{
		ensureNotRegistered();
		for (SchemaElement element : elements) {
			element.ensureNotRegistered();
			this.elements.add(element);
			element.schema = this;
		}
	}
	
	void registerElements() 
	throws InvalidSchemaException
	{
		for (SchemaElement element : elements) register(element);
	}
	
	void register(SchemaElement element)
	throws InvalidSchemaException
	{
		for (SchemaElement child : element.getChildElements()) register(child);
		element.register();
	}

	public Iterator<SchemaElement> iterator() 
	{
		return elements.iterator();
	}

	void ensureNotRegistered()
	{
		if (registered) throw new IllegalStateException("Cannot alter registered schema");
	}

	public boolean isRegistered() 
	{
		return registered;
	}
	
	/** Registers this schema.
	 * Calling this method makes definitions in this schema available to all storage
	 * instances.
	 * Registering the same schema several times has no effect.
	 * @param schema The schema to register.
	 * @throws InvalidSchemaException if the schema is not valid.
	 */
	public void register()
	{
		if (!registered) {
			registerElements();
			registered = true;
		}
	}

}
